from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Server, Comment, Reply


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    class Meta:
        model = User
        fields = ['id', 'username', 'email']


class ReplySerializer(serializers.ModelSerializer):
    """回复序列化器"""
    user = UserSerializer(read_only=True)
    
    class Meta:
        model = Reply
        fields = ['id', 'user', 'content', 'created_at']
        read_only_fields = ['user']
        
    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class CommentSerializer(serializers.ModelSerializer):
    """评论序列化器"""
    user = UserSerializer(read_only=True)
    replies = ReplySerializer(many=True, read_only=True)
    
    class Meta:
        model = Comment
        fields = ['id', 'user', 'content', 'created_at', 'updated_at', 'replies']
        read_only_fields = ['user']
        
    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class ServerSerializer(serializers.ModelSerializer):
    """MCP Server 列表序列化器"""
    
    class Meta:
        model = Server
        fields = [
            'id', 'name', 'name_cn', 'icon', 'provider', 'description', 
            'description_cn', 'category', 'category_cn', 'tags', 
            'is_official', 'is_internal', 'from_site', 'from_site_url',
            'internal_doc_url', 'zone', 'is_deleted', 'created_at', 'updated_at', 'access_mode', 
            'sse_url', 'http_url'
        ]


class ServerDetailSerializer(serializers.ModelSerializer):
    """MCP Server 详情序列化器"""
    comments = CommentSerializer(many=True, read_only=True)
    
    class Meta:
        model = Server
        fields = [
            'id', 'name', 'name_cn', 'icon', 'provider', 'description', 
            'description_cn', 'category', 'category_cn', 'tags',
            'is_official', 'is_internal', 'auth_method', 'dev_language',
            'from_site', 'from_site_url', 'internal_doc_url', 'server_config', 'env_schema',
            'tools', 'readme', 'readme_cn', 'verified', 'comments',
            'zone', 'is_deleted', 'created_at', 'updated_at', 'access_mode', 
            'sse_url', 'http_url'
        ] 